package com.cluster.user.controller;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Vector;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class FileListController {

    private static final String SFTP_HOST = "61.155.146.227";
    private static final String SFTP_USER = "root";
    private static final String SFTP_PASSWORD = "k_!Rc9!UMKVs*P";
    private static final String REMOTE_DIR = "/data/upload_file_rule/620_csv/";

    @GetMapping("/list-files")
    public AjaxResult listFiles() {
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            // 创建 SSH 会话
            JSch jsch = new JSch();
            session = jsch.getSession(SFTP_USER, SFTP_HOST, 22);
            session.setPassword(SFTP_PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 打开 SFTP 通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            // 列出目录中的文件
            Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(REMOTE_DIR);

            // 构建返回结果
            AjaxResult ajaxResult = AjaxResult.success("文件列表获取成功！");
            ajaxResult.put("files", fileList);

            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error("文件列表获取失败: " + e.getMessage());
        } finally {
            // 关闭通道和会话
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
